// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = async(event, co// 云函数入口文件
const cloud = require('wx-server-sdk')
const request = require('request');

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {

  const wxContext = cloud.getWXContext()
  const db = cloud.database();

  if (typeof (event.lon) !== 'Number') {
    event.lon = 90;
  };
  if (typeof (event.lat) !== 'Number') {
    event.lat = 0;
  };

  /************定义监测的异常情况 */
  var info = {
    _openId: wxContext.OPENID, //自身openId
    env: wxContext.ENV,
    unionId: wxContext.UNIONID,
    source: wxContext.SOURCE,
    openId: event.openId, //对象的微信openId
    sex: event.sex,
    age: event.age,
    name: event.name, //微信名
    nick: event.nick, //微信昵称
    mobile: event.mobile,
    temperature: event.temperature,
    identityId: event.identityId, //证件ID
    iidentityType: event.iidentityType, //证件类型
    result: event.result, //情况结果
    timestamp: event.timestamp,
    desc: event.desc,
    img: event.img, //base64存储
    location: new db.Geo.Point(event.lon, event.lat),
    createTime: new Date(),
    status: true
  };

  const url = "http://47.114.59.59:8086/api/info";

  db.collection('info').add({
    data: info
  }).then(res => {
    console.log('create info:', res);
    info.orderNo = res._id;
    info.lat = event.lat;
    info.lon = event.lon;
    /**********数据上传 */
    request({
      url: url,
      method: "POST",
      json: true,
      headers: {
        "content-type": "application/json",
      },
      body: info
    }, function (error, response, body) {
      console.log('body', error, response, body);
      if (!error && response.statusCode == 200) {
        return {
          error: null,
          creatTime: body.createTime
        };
      } else {
        return {
          error: error
        };
      };
    });

  });

}